package com.wzy.springcloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.wzy.springcloud.entities.CommonResult;
import com.wzy.springcloud.entities.Payment;
import com.wzy.springcloud.service.PaymentService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@RestController
public class ClientController {
    // @Value("${service-url.nacos-user-service}")
    private String SERVICE_URL = "http://nacos-payment-provider";
    @Resource
    private RestTemplate restTemplate;

    @GetMapping("/consumer/fallback/{id}")
    // @SentinelResource(value = "fallback", fallback = "handleFallback")
    @SentinelResource(value = "fallback", blockHandler = "blockHandler", fallback = "handleFallback"
            , exceptionsToIgnore = {IllegalArgumentException.class})
    public CommonResult<Payment> fallback(@PathVariable("id") Long id) {
        CommonResult result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/" + id, CommonResult.class, id);
        if (id == 4) {
            throw new IllegalArgumentException("IllegalAccessException,非法的参数异常");
        } else if (result.getData() == null) {
            throw new NullPointerException("NullPointerException,该id没有对应的记录");
        }
        return result;
    }

    public CommonResult handleFallback(@PathVariable("id") Long id, Throwable throwable) {
        Payment payment = new Payment(id, "null");
        return new CommonResult(444, "兜底方案 handleFallback" + throwable.getMessage(), payment);
    }

    //blockHandler
    public CommonResult blockHandler(@PathVariable("id") Long id, BlockException e) {
        Payment aNull = new Payment(id, "null");
        return new CommonResult(445, "blockHandler-sentinel限流," + e.getMessage());
    }

    @Resource
    private PaymentService paymentService;

    @GetMapping("/consumer/paymentSQL/{id}")
    public CommonResult<Payment> paymentSql(@PathVariable("id") Long id) {
        return paymentService.payment(id);
    }


}
